﻿using System.Linq;
using System.Web.Mvc;
using MovingFromPartialViews.Models;

namespace MovingFromPartialViews.Controllers
{
    public class HomeController : Controller
    {
        //
        // GET: /Home/

        public ActionResult Index()
        {
            return View(GetModel());
        }

		[HttpPost]
		public ActionResult Add(NewSubscription subscription)
		{
			var model = GetModel();
			var cat = model.Categories.First(c => c.Name == subscription.CategoryName);
			cat.Subscriptions.Add(new Subscription{Name = subscription.Name ?? string.Empty});

			return Json(model);
		}

		[HttpPost]
		public ActionResult Delete(string subName)
		{
			var model = GetModel();
			var cat = model.Categories.FirstOrDefault(c => c.Subscriptions.Any(s => s.Name == (subName ?? string.Empty)));
			if( cat != null)
				cat.Subscriptions.Remove(cat.Subscriptions.First(s => s.Name == subName));

			return Json(new {subName});
		}

		public ActionResult SubsList()
		{
			return Json(GetModel(), JsonRequestBehavior.AllowGet);
		}

		/// <summary>
		/// For a demo app, just store the data in the session for now
		/// </summary>
		/// <returns></returns>
		private IndexModel GetModel()
		{
			if (Session["model"] == null)
			{
				var cats = new[]
		        {
			        new Category
				        {
					        Name = "ASP.NET",
					        Subscriptions =
						        {
							        new Subscription
								        {
									        Name = "ASP.NET Community Spotlight",
									        UnreadCount = 5,
									        Url = "http://www.asp.net/rss/spotlight"
								        },
							        new Subscription {Name = "ScottGu's Blog", UnreadCount = 2, Url = "http://weblogs.asp.net/scottgu/"}
						        }
				        },
			        new Category
				        {
					        Name = "Async",
					        Subscriptions =
						        {
							        new Subscription
								        {
									        Name = "Bill Wagner Async",
									        UnreadCount = 0,
									        Url = "http://www.srtsolutions.com/tag/async"
								        }
						        }
				        },
			        new Category
				        {
					        Name = "Windows 8",
					        Subscriptions =
						        {
							        new Subscription
								        {
									        Name = "Blankenblog",
									        UnreadCount = 1,
									        Url = "http://feeds.feedburner.com/blankenthoughts"
								        }
						        }
				        },
		        };
				var model = new IndexModel { Categories = cats };
				Session["model"] = model;
			}

			return Session["model"] as IndexModel;
		}
    }
}
